package com.example.burnafterreading.service;

import com.example.burnafterreading.model.Message;
import com.example.burnafterreading.repository.MessageRepository;
import com.example.burnafterreading.dto.MessageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Base64;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class MessageService {
    
    private static final int MAX_FAILED_ATTEMPTS = 3;
    
    private static final Logger logger = LoggerFactory.getLogger(MessageService.class);
    
    @Autowired
    private MessageRepository messageRepository;
    
    @Value("${image.storage.path}")
    private String imageStoragePath;
    
    public Message createMessage(MessageRequest request) {
        logger.info("Creating message with title: {}", request.getTitle());
        Message message = new Message();
        message.setContent(request.getContent());
        message.setAccessKey(UUID.randomUUID().toString());
        message.setRead(false);
        message.setCreatedAt(LocalDateTime.now());
        
        // 设置标题
        message.setTitle(request.getTitle() != null && !request.getTitle().trim().isEmpty() 
            ? request.getTitle() 
            : "阅后即焚消息");
        
        // 设置密码保护
        message.setHasPassword(request.isHasPassword());
        if (request.isHasPassword() && request.getPassword() != null) {
            message.setPassword(request.getPassword());
            message.setFailedAttempts(0);
        }
        
        // 处理图片
        if (request.getImage() != null && request.getImageType() != null) {
            try {
                String imagePath = uploadImageToStorage(request.getImage(), request.getImageType().split("/")[1]); // 上传图片并获取路径
                message.setImagePath(imagePath); // 存储图片路径
            } catch (IOException e) {
                throw new RuntimeException("上传图片失败: " + e.getMessage());
            }
        }
        
        return messageRepository.save(message);
    }
    
    @Transactional
    public Message readMessage(String accessKey, String password) throws IOException {
        Message message = messageRepository.findByAccessKey(accessKey)
                .orElseThrow(() -> new RuntimeException("消息不存在或已被删除"));
        
        if (message.isRead()) {
            throw new RuntimeException("消息已被阅读，无法再次查看");
        }
        
        // 检查密码保护
        if (message.isHasPassword()) {
            if (password == null || !password.equals(message.getPassword())) {
                throw new RuntimeException("密码错误，请重试");
            }
        }

        // 读取图片
        String imagePath = message.getImagePath();
        if (imagePath != null) {
            byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath));
            String base64Image = Base64.getEncoder().encodeToString(imageBytes);
            if (base64Image.contains(",")) {
                base64Image = base64Image.split(",")[1];
            }
            // 移除前缀后解码
            message.setImage(Base64.getDecoder().decode(base64Image));
        }

        message.setRead(true);
        messageRepository.save(message);
        return message;
    }
    
    public boolean checkPassword(String accessKey, String password) {
        Message message = messageRepository.findByAccessKey(accessKey)
                .orElseThrow(() -> new RuntimeException("消息不存在或已被删除"));
                
        if (message.isRead()) {
            throw new RuntimeException("消息已被阅读，无法再次查看");
        }
        
        if (!message.isHasPassword()) {
            return true;
        }
        
        if (message.getFailedAttempts() >= MAX_FAILED_ATTEMPTS) {
            throw new RuntimeException("密码错误次数过多，消息已被锁定");
        }
        
        return password != null && password.equals(message.getPassword());
    }
    
    public boolean isPasswordProtected(String accessKey) {
        Message message = messageRepository.findByAccessKey(accessKey)
                .orElseThrow(() -> new RuntimeException("消息不存在或已被删除"));
        return message.isHasPassword();
    }
    
    private String uploadImageToStorage(String image, String imageType) throws IOException {
        String fileName = UUID.randomUUID().toString() + "." + imageType;
        Path filePath;
        if (System.getProperty("os.name").toLowerCase().contains("win")) {
            // 当前操作系统是 Windows
            filePath = Paths.get("d:/temp", fileName);
        } else {
            // 当前操作系统不是 Windows
            filePath = Paths.get(imageStoragePath, fileName);
        }
//        filePath = Paths.get(imageStoragePath, fileName);
        String base64Image = image;
        if (base64Image.contains(",")) {
            base64Image = base64Image.split(",")[1];
        }
        // 移除前缀后解码
        byte[] imageBytes = Base64.getDecoder().decode(base64Image);
        Files.write(filePath, imageBytes);
        return filePath.toString();
    }
}
